<template>
  <div class="bg-white sticky top-0 left-0 z-10 dark:bg-zinc-900">
    <ul
      ref="ulTarget"
      class="relative flex overflow-x-auto p-1 text-xs text-zinc-600 overflow-hidden"
    >
      <!-- 滑块 -->
      <li
        ref="sliderTarget"
        class="absolute h-[22px] bg-zinc-900 rounded-lg duration-200"
        :style="sliderStyle"
      ></li>
      <li
        class="shadow-l-white z-20 fixed top-0 right-[-1px] h-4 px-1 flex items-center bg-white dark:bg-zinc-900 dark:shadow-l-zinc"
        @click="handleMenu"
      >
        <m-svg-icon class="w-1.5 h-1.5" name="hamburger"></m-svg-icon>
      </li>
      <li
        class="shrink-0 px-1.5 py-0.5 z-10 duration-200 last:mr-4 dark:bg-zinc-800"
        v-for="(item, index) in $store.getters.category"
        :key="item.id"
        :ref="itemRefs"
        @click="changeCurrentCategroy(item)"
        :class="{
          'text-zinc-100': $store.getters.currentCategorysIndex === index
        }"
      >
        {{ item.name }}
      </li>
    </ul>
  </div>
  <m-popup v-model="showMenu">
    <menuVue @onItemClick="changeCurrentCategroy"></menuVue>
  </m-popup>
</template>
<script setup>
import { ref, onBeforeUpdate, watch } from 'vue'
import menuVue from '../../menu/index.vue'
import { useScroll } from '@vueuse/core'
import { useStore } from 'vuex'
const store = useStore()
const sliderStyle = ref({
  transform: 'translateX(0px)',
  width: '29px'
})
let itemRefsArr = []
const itemRefs = (itemRef) => {
  if (itemRef) {
    itemRefsArr.push(itemRef)
  }
}

onBeforeUpdate(() => {
  itemRefsArr = []
})
const ulTarget = ref(null)
const { x: ulScrollLeft } = useScroll(ulTarget)
const changeCurrentCategroy = (item) => {
  store.commit('app/setCurrentCategorys', item)
}
watch(
  () => store.getters.currentCategorysIndex,
  () => {
    const { width, left } =
      itemRefsArr[store.getters.currentCategorysIndex].getBoundingClientRect()
    sliderStyle.value = {
      transform: `translateX(${left + ulScrollLeft.value - 10}px)`,
      width: `${width}px`
    }
  }
)
const showMenu = ref(false)
const handleMenu = () => {
  showMenu.value = true
}
const itemClick = (e) => {
  currentCategroyIndex.value = e
  showMenu.value = false
}
</script>
